<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h3>WebSocket测试，在<span style="color:red">控制台</span>查看测试信息输出！</h3>
<textarea id="content" style="height: 300px;width: 680px">
</textarea>


<script type="text/javascript">
    var socket;
    // 发送心跳数据
    var heartCheck = {
        timeout: 60000,//60s
        timeoutObj: null,
        reset: function () {
            clearInterval(this.timeoutObj);
            this.start();
        },
        start: function () {
            this.timeoutObj = setInterval(function () {
                if (socket.readyState == 1) {
                    socket.send("ping");
                }
            }, this.timeout)
        }
    };
    if (typeof (WebSocket) == "undefined") {
        console.log("遗憾：您的浏览器不支持WebSocket");
    } else {
        console.log("恭喜：您的浏览器支持WebSocket");

        //实现化WebSocket对象
        //指定要连接的服务器地址与端口建立连接
        //注意ws、wss使用不同的端口。我使用自签名的证书测试，
        //无法使用wss，浏览器打开WebSocket时报错
        //ws对应http、wss对应https。
        //  /ws/{userId}
        socket = new WebSocket("ws://10.8.0.4:40500/ws/10000");
        //连接打开事件
        socket.onopen = function (evnt) {
            console.log("onopen: ", evnt);
            heartCheck.start();
        };
        //收到消息事件
        socket.onmessage = function (evnt) {
            console.log("onmessage: ", evnt);
            heartCheck.reset();
            var textarea = document.getElementById("content");
            textarea.value = textarea.value + evnt.data + '\n';
            textarea.scrollTop = textarea.scrollHeight;
        };
        //连接关闭事件
        socket.onclose = function (evnt) {
            console.log("Socket已关闭");
            if (evnt.code != 4500) {
                //4500为服务端在打开多tab时主动关闭返回的编码
                reconnect();//重连
            }
        };
        //发生了错误事件
        socket.onerror = function (evnt) {
            console.log("onerror: ", evnt);
        }

        //窗口关闭时，关闭连接
        window.unload = function () {
            socket.close();
        };
    }
</script>
</body>
</html>
